from typing import Optional
from .base_dao import getDatabaseSession
from app.dao.models import UserFeedBack


class UserFeedbackDao:

    @classmethod
    def create_feedback(cls, feedback: UserFeedBack) -> UserFeedBack:
        with getDatabaseSession(False) as session:
            session.add(feedback)
            session.commit()
            session.refresh(feedback)
            return feedback

    @classmethod
    def get_all_feedbacks(cls) -> list[UserFeedBack]:
        with getDatabaseSession() as session:
            return (
                session.query(UserFeedBack)
                .order_by(UserFeedBack.created_at.desc())
                .all()
            )

    @classmethod
    def get_feedback_by_id(cls, feedback_id: str) -> Optional[UserFeedBack]:
        with getDatabaseSession() as session:
            return (
                session.query(UserFeedBack)
                .filter(UserFeedBack.id == feedback_id)
                .first()
            )

    @classmethod
    def update_feedback_status(cls, feedback_id: str, status: int) -> bool:
        with getDatabaseSession(False) as session:
            feedback = (
                session.query(UserFeedBack)
                .filter(UserFeedBack.id == feedback_id)
                .first()
            )
            if not feedback:
                return False
            feedback.status = status
            session.commit()
            return True

    @classmethod
    def get_feedbacks_by_student_id(cls, student_id: str) -> list[UserFeedBack]:
        with getDatabaseSession() as session:
            return (
                session.query(UserFeedBack)
                .filter(UserFeedBack.student_id == student_id)
                .order_by(UserFeedBack.created_at.desc())
                .all()
            )
